package com.neusoft.controller;


import com.neusoft.feign.CartFeignClient;
import com.neusoft.feign.CreditFeignClient;
import com.neusoft.feign.RedenvFeignClient;
import com.neusoft.feign.VirtualwalletFeignClient;
import com.neusoft.po.Cart;
import com.neusoft.po.CommonResult;
import com.neusoft.po.Orders;
import com.neusoft.po.Redenv;
import com.neusoft.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import sun.util.logging.resources.logging;

import java.math.BigDecimal;
import java.util.List;


@RestController
@RequestMapping("/OrdersController")
@RefreshScope
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    @Resource
    private CartFeignClient cartFeignClient;
    @Resource
    private CreditFeignClient creditFeignClient;
    @Resource
    private RedenvFeignClient redenvFeignClient;
    @Resource
    private VirtualwalletFeignClient virtualwalletFeignClient;

    @RequestMapping(value = "createOrders",method = RequestMethod.POST)
    public CommonResult<Integer> createOrders(@RequestBody Orders orders) throws Exception{

        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        CommonResult<List<Cart>> result = cartFeignClient.listCart(orders.getUserId(), orders.getBusinessId());

        if (result.getCode() == 200) {
            CommonResult<Integer> clear_result = cartFeignClient.removeCart(orders.getUserId(), orders.getBusinessId());
            return new CommonResult(200, "success（10600）", ordersService.createOrders(result.getResult(),orders));
        }
        return new CommonResult(500, "创建订单失败", -1);
    }

    @RequestMapping(value = "getOrdersById",method = RequestMethod.GET)
    public CommonResult<Orders> getOrdersById(@RequestParam Integer orderId) throws Exception{
        return new CommonResult(200, "success（10600）", ordersService.getOrdersById(orderId));
    }

    @RequestMapping(value="listOrdersByUserId",method = RequestMethod.GET)
    public CommonResult<List> listOrdersByUserId(@RequestParam String userId) throws Exception{
        return new CommonResult(200, "success（10600）", ordersService.listOrdersByUserId(userId));
    }

    //积分+虚拟钱包支付
    //number为需要支付的积分
    @PostMapping("/payByCreditWallet/{orderId}/{number}")
    public CommonResult<Integer> payByCreditWallet(@PathVariable("orderId") Integer orderId,
                                     @PathVariable("number") Integer number) throws Exception{
        //查询order订单
        Orders orders = ordersService.getOrdersById(orderId);
        //查询需要支付的总金额
        BigDecimal balance=new BigDecimal(orders.getOrderTotal());
        //需要虚拟钱包支付的金额数
        //调用远程接口得到总积分数量
        CommonResult<Integer> result = creditFeignClient.getTotalCreditByUserId(orders.getUserId());
        if(result.getCode()==200) {
            Integer totalCredit= result.getResult();
            //将总积分转为BiGDecimal形式
            BigDecimal totalCreditNum=new BigDecimal(totalCredit);
            //如果总积分大于需要支付的积分
            if (totalCredit >= number) {
                //支付number数量的积分
                CommonResult<Integer> result1 = creditFeignClient.payoutByUserId(orders.getUserId(), number);
                balance=balance.subtract(new BigDecimal(number));
            }else{
                //支付不了所需的积分
                return new CommonResult(500, "积分不足", -1);
            }
        }
        //用户付钱
        Integer state=ordersService.updateOrders(balance.doubleValue(),orders.getOrderId());
        //如果能够修改状态成功，则支付相应金额,给用户充值1积分
        if(state==1){
            Integer result1 = virtualwalletFeignClient.payoutByUserId(orders.getUserId(), balance).getResult();
            creditFeignClient.rechargeByUserId(orders.getUserId(),1);
            return new CommonResult(200, "支付成功", ordersService.pay(orders.getOrderId()));
        }else{
            return new CommonResult(500, "支付失败", -1);
        }


    }
    @PostMapping("/payByRedEnvWallet/{orderId}/{redenvId}")
    public CommonResult<Integer> payByRedEnvWallet(@PathVariable("orderId") Integer orderId,
                                     @PathVariable("redenvId") Integer redenvId) throws Exception{
        //查询order订单
        Orders orders = ordersService.getOrdersById(orderId);
        //查询需要支付的总金额
        BigDecimal balance=new BigDecimal(orders.getOrderTotal());
        //调用远程接口得到红包实体
        CommonResult<Redenv> redenv = redenvFeignClient.getRedenvByRedenvId(redenvId);
        if(redenv.getCode()==200) {
            //得到对应红包金额
            BigDecimal redenvNum = redenv.getResult().getBalance();
            //如果红包金额大于需要支付的金额
            if (redenvNum.compareTo(redenvNum)==1) {
                return new CommonResult(500, "红包大于当前金额", -1);
            }else{
                //红包金额全支付，剩下的钱虚拟钱包支付
                CommonResult<Integer> result = redenvFeignClient.useRedenvByRedenvId(redenvId);
                Integer redEnvState = result.getResult();
                if(redEnvState!=1){
                    return new CommonResult(500,"红包无法使用",-1);
                }else{
                    //减去红包金额就是待支付的钱
                    BigDecimal subNum = balance.subtract(redenvNum);
                    //用户付钱
                    Integer state=ordersService.updateOrders(subNum.doubleValue(),orders.getOrderId());
                    //如果能够修改状态成功，则支付相应金额,给用户充值1积分
                    if(state==1){
                        Integer result1 = virtualwalletFeignClient.payoutByUserId(orders.getUserId(), subNum).getResult();
                        creditFeignClient.rechargeByUserId(orders.getUserId(),1);
                        return new CommonResult(200, "支付成功", ordersService.pay(orders.getOrderId()));
                    }else{
                        return new CommonResult(500, "支付失败", -1);
                    }
                }
            }
        }
        //用户付钱
        Integer state=ordersService.updateOrders(balance.doubleValue(),orders.getOrderId());
        //如果能够修改状态成功，则支付相应金额,给用户充值1积分
        if(state==1){
            Integer result1 = virtualwalletFeignClient.payoutByUserId(orders.getUserId(), balance).getResult();
            creditFeignClient.rechargeByUserId(orders.getUserId(),1);
            return new CommonResult(200, "支付成功", result1);
        }else{
            return new CommonResult(500, "支付失败", -1);
        }
    }
    @PostMapping("/pay/{orderId}")
    public CommonResult<Integer> payByWallet(@PathVariable("orderId") Integer orderId) throws Exception{
        Orders orders = ordersService.getOrdersById(orderId);
        //用户付钱
        Integer e = virtualwalletFeignClient.payoutByUserId(orders.getUserId(),new BigDecimal(orders.getOrderTotal())).getResult();
        creditFeignClient.rechargeByUserId(orders.getUserId(),1);
        return new CommonResult(200, "付钱情况：e", ordersService.pay(orders.getOrderId()));
    }
}
